package com.stonedt.spider.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @Author: 康涵博
 * @ClassName: ApiCallUtil
 * @Time: 2024/4/29 16:05
 * @Description:
 */
public class ApiCallUtil {
    // 定义一个静态方法，用于发送POST请求
    public static String doPost(String url, JSONObject json){
        // 创建一个HttpClient对象
        HttpClient httpClient = new HttpClient();
        // 创建一个PostMethod对象，传入请求的URL
        PostMethod postMethod = new PostMethod(url);

        // 添加请求头信息
        postMethod.addRequestHeader("token", "hfweuiw74h543fq8nqf983hf2338qj3h87h");
        postMethod.addRequestHeader("accept", "*/*"); // 设置接受任意类型的数据
        postMethod.addRequestHeader("connection", "Keep-Alive"); // 设置连接保持活跃
        // 设置请求头的Content-Type为application/json;charset=GBK，表示发送的数据是JSON格式，字符集为UTF-8
        postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
        // 设置请求头的User-Agent，模拟浏览器发送请求
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        // 添加请求参数，从json对象中获取prompt的值，并添加到请求参数中
//        postMethod.addParameter("prompt", json.getString("prompt"));

        RequestEntity requestEntity = new StringRequestEntity(json.toString());
        postMethod.setRequestEntity(requestEntity);

        // 初始化响应结果字符串
        String res = "";
        try {
            // 执行请求，获取响应状态码
            int code = httpClient.executeMethod(postMethod);
            // 如果状态码为200，表示请求成功
            if (code == 200){
                // 获取响应体内容，并转换为字符串
                byte[] responseBody = postMethod.getResponseBody();
                res = new String(responseBody, StandardCharsets.UTF_8);
                // 打印响应结果
                System.out.println(res);
            }else {
                // 如果状态码不为200，打印错误信息
                System.out.println("请求失败，请检查大模型接口或者其他问题。状态码：" + code);
            }
        } catch (IOException e) {
            // 如果发生异常，打印异常信息
            e.printStackTrace();
        }
        // 返回响应结果
        return res;
    }

    // 添加一个静态方法，用于读取properties文件中的接口访问地址
    public static String getUrlFromProperties(String key) {
        Properties properties = new Properties();
        try {
            // 加载properties文件
            properties.load(new FileInputStream("config/application.properties"));
            // 获取接口访问地址
            return properties.getProperty(key);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

